import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import config from '@/config'
import contextUtils from '@/libs/contextUtils'
import storeModules from '@/store/modules'

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'hash'
})

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = contextUtils.getToken()

  if (!token || token === '') {
    // 未登录
    config.unLoginHandler(contextUtils, config, to, from, next)
  } else {
    config.amendLocationHandler(contextUtils)
    // 已登录,先取用户信息
    store.dispatch('getUserInfo').then(user => {
      // console.log('用户信息加载成功', user)

      // 处理模块懒加载
      if (to.meta.storeModules && to.meta.storeModules.length > 0) {
      // 从路由元数据中取待加载模块
        let checkPromies = to.meta.storeModules.map((item, index) => {
          let storeModule = storeModules.filter(storeModule => {
            return storeModule.name === item
          })
          return store.dispatch('findModule', storeModule[0])
        })
        // 检查待加载模块，过滤去已加载模块
        Promise.all(checkPromies).then(moduleLoadStates => {
          return new Promise((resolve, reject) => {
            let waitLoadModules = moduleLoadStates.filter(moduleLoadState => !moduleLoadState.loaded)
            resolve(waitLoadModules)
          })
        }, error => console.error(error)).then(waitLoadModules => {
        // 构建待加载的promise集合，共同发起处理
          let loadPromises = waitLoadModules.map((item, index) => {
            return item.storeModule
          })
          return Promise.all(loadPromises)
        }).then(modules => {
        // 全部加载后，注册模块，记录加载状态
          modules.forEach((item, index) => {
            if (item.default.storeName) {
              store.registerModule(item.default.storeName, item.default, {
                preserveState: true,
                runInNewContext: 'once'
              })
              store.dispatch('addLoadedModule', item.default.storeName)
              // console.log(store)
            } else {
              console.error('模块的StoreName未定义')
            }
          })
          next()
        })
      } else {
        next()
      }
    })
  }
})

router.afterEach(to => {
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
